import Vue from "vue";
import Vuex from "vuex";
import { login } from "@/http/api";
Vue.use(Vuex);

export default new Vuex.Store({
  state: {
    token: localStorage.getItem("token") || "",
    username: localStorage.getItem("username") || "",
  },
  mutations: {
    SET_TOKEN(state, data) {
      state.token = data;
      localStorage.setItem("token", data);
    },
    SET_USER_NAME(state, data) {
      state.username = data;
      localStorage.setItem("username", data);
    },
  },
  actions: {
    //封装登录action
    async login({ commit }, val) {
      try {
        const {
          data: { token, username },
        } = await login(val);
        commit("SET_TOKEN", token);
        commit("SET_USER_NAME", username);
      } catch (error) {
        return error;
      }
    },
    //退出
    signOut({ commit }) {
      commit("SET_TOKEN", "");
      commit("SET_USER_NAME", "");
    },
  },
  modules: {},
});
